package com.zf.yichat.api.controller.tickets;


import com.github.pagehelper.PageHelper;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.TicketMarketRequest;
import com.zf.yichat.api.dto.request.TicketTradeRequest;
import com.zf.yichat.api.dto.request.TicketsRequest;
import com.zf.yichat.dto.PacketReceiveDto;
import com.zf.yichat.dto.TicketMarketDto;
import com.zf.yichat.dto.TicketsDto;
import com.zf.yichat.model.StUserTicket;
import com.zf.yichat.service.BalanceService;
import com.zf.yichat.service.TicketsService;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 门票系统
 */
@RestController
@RequestMapping("tickets")
@Slf4j
public class TicketsController extends BaseController {


    @Autowired
    private TicketsService ticketsService;

    @Autowired
    private BalanceService balanceService;
    /**
     * 查询用户门票列表
     * @return
     */
    @PostMapping("queryUserTickets")
    public FsResponse queryUserTickets(@RequestBody TicketsRequest request) {

        Long userId = getUserId();
        if (null == userId) {
            return FsResponseGen.failMsg("参数错误【userId】");
        }

        Integer status = request.getStatus();
        List<StUserTicket> list = ticketsService.queryUserTickets(userId, status);
        ArrayList<TicketsDto> ticketsDtos = new ArrayList<>();
        for (StUserTicket ticket : list) {
            try {
                TicketsDto dto = new TicketsDto();
                BeanUtils.copyProperties(ticket, dto);

                // 门票基本信息
                String ticketType = dto.getTicketType();
                if (StUserTicket.TYPE_OFFICIAL.equals(ticketType)) {
                    dto.setTicketName("海报门票");
                    dto.setTicketDesc("海报门票描述");
                    dto.setTicketAvatar("");
                    dto.setPeriodValidity("2024-10-22");
                }
                if (StUserTicket.TYPE_REGISTER.equals(ticketType)) {
                    dto.setTicketName("注册好礼");
                    dto.setTicketDesc("注册好礼描述");
                    dto.setTicketAvatar("");
                    dto.setPeriodValidity("2024-10-22");
                }

                Long uId = ticket.getUserId();
                String encodeUserId = N3d.encode(uId);
                dto.setUserId(encodeUserId);
                dto.setPurposeType(TicketsDto.PURPOSE_TYPE_ACTIVATION);
                ticketsDtos.add(dto);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("用户id加密错误！");
            }
        }
        return FsResponseGen.successData(ticketsDtos);
    }

    /**
     * 用户扫描官方邀请码赠送门票
     * @return
     */
    @PostMapping("officialInvitationTickets")
    public FsResponse officialInvitationTickets(@RequestBody TicketsRequest request) {

        Long userId = getUserId();
        if (null == userId) {
            return FsResponseGen.failMsg("参数错误【userId】");
        }

        String ticketCode = request.getTicketCode();
        if (null == ticketCode) {
            return FsResponseGen.failMsg("参数错误【ticketCode】");
        }
        return ticketsService.officialInvitationTickets(userId, ticketCode);
    }


    /**
     * 激活用户门票
     * @return
     */
    @PostMapping("activateUserTickets")
    public FsResponse activateUserTickets(@RequestBody TicketsRequest request) throws Exception {

        Long adminUserId = getUserId();
        if (null == adminUserId) {
            return FsResponseGen.failMsg("参数错误【userId】");
        }

        String ticketCode = request.getTicketCode();
        if (null == ticketCode) {
            return FsResponseGen.failMsg("参数错误【ticketCode】");
        }

        String customerUserId = request.getUserId();
        Long userId = N3d.decode(customerUserId);
        return ticketsService.activateUserTickets(adminUserId, ticketCode, userId);
    }

    /**
     * 门票市场列表接口
     * @return
     */
    @PostMapping("queryTicketMarketList")
    public FsResponse queryTicketMarketList(@RequestBody TicketMarketRequest request) throws Exception {

        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();

        if (null == pageNo) {
            pageNo = 1;
        }
        if(null == pageSize){
            pageSize = 10;
        }

        Long userId = getUserId();
        Integer showType = request.getShowType();

        PageHelper.startPage(pageNo, pageSize);
        return DtoChangeUtils.getPageList(ticketsService.queryTicketMarketList(showType, userId), data -> {
            TicketMarketDto marketDto = new TicketMarketDto();
            BeanUtils.copyProperties(data, marketDto);
            return marketDto;
        });
    }

    /**
     * 门票上架接口
     * @return
     */
    @PostMapping("ticketListing")
    public FsResponse ticketListing(@RequestBody TicketMarketRequest request) throws Exception {

        Long userId = getUserId();

        BigDecimal ticketPrice = request.getTicketPrice();
        if (null == ticketPrice){
            ticketPrice = BigDecimal.ZERO;
        }

        String ticketTitle = request.getTicketTitle();
        if (StringUtils.isBlank(ticketTitle)) {
            return FsResponseGen.failMsg("上架标题为空！");
        }

        Integer ticketId = request.getUserTicketId();
        if (null == ticketId) {
            return FsResponseGen.failMsg("上架门票ID为空！");
        }
        return ticketsService.ticketListing(userId, ticketId, ticketPrice, ticketTitle);
    }


    /**
     * 门票编辑接口-修改门票上架标题，价格，也可用于下架
     * @return
     */
    @PostMapping("ticketEdit")
    public FsResponse ticketEdit(@RequestBody TicketMarketRequest request) throws Exception {

        Integer marketId = request.getId();
        if (null == marketId) {
            return FsResponseGen.failMsg("市场门票ID为空！");
        }

        BigDecimal ticketPrice = request.getTicketPrice();
        if (null == ticketPrice){
            ticketPrice = BigDecimal.ZERO;
        }

        return ticketsService.ticketEdit(marketId, ticketPrice, request.getTicketTitle(), request.getTicketStatus());
    }


    /**
     * 门票购买接口
     * @return
     */
    @PostMapping("ticketPurchase")
    public FsResponse ticketPurchase(@RequestBody TicketTradeRequest request) throws Exception {

        // 购买人
        Long userId = getUserId();

        Integer marketId = request.getId();
        if (null == marketId) {
            return FsResponseGen.failMsg("市场门票ID为空！");
        }

        // 门票所有者ID
        String ownerId = request.getUserId();

        // 支付密码
        String password = request.getPassword();
        if (StringUtils.isBlank(password)) {
            return FsResponseGen.failMsg("支付密码参数错误！");
        }

        balanceService.checkPassword(userId, password);
        return ticketsService.ticketPurchase(userId, ownerId, marketId);
    }


    /**
     * 门票记录接口
     * @return
     */
    @PostMapping("ticketRecord")
    public FsResponse ticketRecord(@RequestBody TicketMarketRequest request) throws Exception {

        // 购买人
        Long userId = getUserId();
        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();

        if (null == pageNo) {
            pageNo = 1;
        }
        if(null == pageSize){
            pageSize = 10;
        }

        Integer recordStatus = request.getRecordStatus();
        if (null == recordStatus) {
            recordStatus = TicketMarketRequest.RECORD_STATUS_0;
        }

        return ticketsService.ticketRecord(userId, recordStatus, pageNo, pageSize);
    }



}
